Arithmetic operators

From Cppreference

Jump to: navigation, search

Returns the result of specific arithmetic operation.

Operator name Syntax Over​load​able Prototype examples (for class T​)
Inside class definition Outside class definition
addition a + b Yes ​T& T::operator +(const T2 &b) const; ​T& operator +(const T &a, const T2 &b);
subtraction a - b Yes ​T& T::operator -(const T2 &b) const; ​T& operator -(const T &a, const T2 &b);
multiplication a * b Yes ​T& T::operator *(const T2 &b) const; ​T& operator *(const T &a, const T2 &b);
division a / b Yes ​T& T::operator /(const T2 &b) const; ​T& operator /(const T &a, const T2 &b);
modulo a % b Yes ​T& T::operator %(const T2 &b) const; ​T& operator %(const T &a, const T2 &b);
bitwise AND a & b Yes ​T& T::operator &(const T2 &b) const; ​T& operator &(const T &a, const T2 &b);
bitwise OR a | b Yes ​T& T::operator |(const T2 &b) const; ​T& operator |(const T &a, const T2 &b);
bitwise XOR a ^ b Yes ​T& T::operator ^(const T2 &b) const; ​T& operator ^(const T &a, const T2 &b);
bitwise left shift a << b Yes ​T& T::operator <<(const T2 &b) const; ​T& operator <<(const T &a, const T2 &b);
bitwise right shift a >> b Yes ​T& T::operator >>(const T2 &b) const; ​T& operator >>(const T &a, const T2 &b);
Notes
  • All operators usually return a value of type ​T​. However, essentially ny type can be returned (including void,
    i.e. no return value), yet this is unintuitive and thus defeats the purpose of the operators.
  • T2 can be any type including T

[edit] Explanation

All arithmetic operators compute the result of specific arithmetic operation and returns its result. The arguments are not modified.

[edit] See also

Operator precedence

Common operators
assignment increment
decrement
arithmetic comparison member
access
other
​a = b

a = rvalue
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b​

++a

--a
a++
a--

​a + b

a - b
a * b
a / b
a % b
a & b
a | b
a ^ b
a << b
a >> b​

​a == b

a != b
a < b
a > b
a <= b
a >= b​

​a[b]

*a
&a
a->b
a.b
a->*b
a.*b​

​a(...)

a, b
(type) a
? :

Special operators

static_cast converts one type to another compatible type
dynamic_cast converts virtual base class to derived class
const_cast converts type to compatible type with different cv qualifiers
reinterpret_cast converts type to incompatible type
new allocates memory
delete deallocates memory
sizeof queries the size of a type
typeid queries the type information of a type
noexcept checks if an expression can throw an exception (C++0x)
alignof queries alignment requirements of a type (C++0x)

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages